package com.tbvtc.agriculturalcreditchainserver2025.async;

import com.google.gson.JsonArray;
import com.google.gson.JsonParser;
import com.tbvtc.agriculturalcreditchainserver2025.exception.FoodException;
import com.tbvtc.agriculturalcreditchainserver2025.properties.ContractAdressProperties;
import com.tbvtc.agriculturalcreditchainserver2025.utils.BlockBaseUtils;
import com.tbvtc.agriculturalcreditchainserver2025.utils.BlockchainUtils;
import com.tbvtc.agriculturalcreditchainserver2025.utils.ResultCodeEnum;
import com.tbvtc.agriculturalcreditchainserver2025.utils.UserType;
import com.tbvtc.agriculturalcreditchainserver2025.vo.Pest.getCropPestReportVo;
import com.tbvtc.agriculturalcreditchainserver2025.vo.farmerVo.FoodReportVo;
import lombok.RequiredArgsConstructor;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.CompletableFuture;

@Service
@RequiredArgsConstructor // 自动注入
public class AsyncQueryService {
    private final BlockchainUtils blockchainUtils;
    private final BlockBaseUtils blockBaseUtils;
    private final ContractAdressProperties contractAdressProperties;
    @Async("blockchainQueryExecutor") // 异步执行
    public CompletableFuture<FoodReportVo> getCropReport(String cropName, Integer batchId) {
        try {
            List<Object> list = blockchainUtils.callContract("FarmerManagement",
                    "getReport",
                    contractAdressProperties.getFarmerManagementAddress(),
                    List.of(cropName, batchId),
                    blockBaseUtils.getPemFilePath(UserType.FARMER));
            // 解析JSON字符串
            FoodReportVo foodReportVo = new FoodReportVo(list);

            return CompletableFuture.completedFuture(foodReportVo); // 返回CompletableFuture对象
        } catch (Exception e) {
            return CompletableFuture.failedFuture(e);
        }

    }
    @Async("blockchainQueryExecutor")
    public CompletableFuture<getCropPestReportVo> getCropPestReport(String cropName, Integer batchId){
        try {
            List<Object> list = blockchainUtils.callContract(
                    "FarmerManagement"
                    , "getPestReport"
                    , contractAdressProperties.getFarmerManagementAddress()
                    , List.of(cropName,batchId)
                    , blockBaseUtils.getPemFilePath(UserType.FARMER));

            getCropPestReportVo reportVo = new getCropPestReportVo(list);
            reportVo.setCropName(cropName);
            return CompletableFuture.completedFuture(reportVo);
        } catch (Exception e) {
            throw new FoodException(ResultCodeEnum.FAILED_TO_QUERY);
        }
    }

}
